﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Meqs.Entity;
using Meqs.Entity.Views;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;

public partial class Credit_Teacher_Reprots_CauseTermEval : ContainerBasePage
{
    private CauseFormula causeFormula;
    private CauseLevelTool causeLevelTool;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            causeLevelTool = new CauseLevelTool(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, SchoolMark);
            BindSchoolYear();
            selYear_TextChanged(selYear, new EventArgs());
            selClass_TextChanged(selClass, new EventArgs());
        }
    }

    /// <summary>
    /// 绑定学期下拉框
    /// </summary>
    protected void BindSchoolYear()
    {
        //Hashtable ht = new Hashtable();
        //ht.Add("SchoolMark", SchoolMark);
        //IList<StuCauseEvalHistory> historyList = Container<IStuCauseEvalHistoryLogic>.Instance.FindAll(ht);
        //if (historyList == null || historyList.Count < 1)
        //{
        //    selYear.Items.Add(new ListItem("没有历史数据", "-1"));
        //}
        //IList<String> strList = new List<String>();
        //if (historyList != null)
        //    foreach (StuCauseEvalHistory history in historyList)
        //    {
        //        String value = String.Format("{0},{1}", history.SchoolYear, history.Term);
        //        if (!strList.Contains(value))
        //        {
        //            int year = 0;
        //            int term = 0;
        //            if (!Int32.TryParse(history.SchoolYear.ToString(), out year))
        //                return;
        //            if (!Int32.TryParse(history.Term.ToString(), out term))
        //                return;
        //            String str = Common.ConvertYearAndTerm(year, term);
        //            selYear.Items.Add(new ListItem(str, value));
        //            strList.Add(value);
        //        }
        //    }

        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", si.SchoolMark);
        IList<TermInfo> terms = Container<ITermInfoLogic>.Instance.FindAll(ht);
        foreach (TermInfo term in terms)
        {
            String str = Common.ConvertYearAndTerm(term.SchoolYear, term.Term);
            String value = String.Format("{0},{1}", term.SchoolYear, term.Term);
            selYear.Items.Add(new ListItem(str, value));
        }
    }

    /// <summary>
    /// 绑定学科下拉框
    /// </summary>
    protected void BindSubject(int grade)
    {
        selSubject.Items.Clear();
        IList<GlobalCauseInfo> subjectList = Container<IGlobalCauseInfoLogic>.Instance.SelectSchoolCause(SchoolMark, 1);
        if (subjectList == null || subjectList.Count < 1)
        {
            selSubject.Items.Add(new ListItem("没有科目数据", "-1"));
            return;
        }
        Hashtable ht = new Hashtable();
        ht.Add("Grade", grade);
        ht.Add("SchoolMark", SchoolMark);
        IList<CouseGradeInfo> cgList = Container<ICouseGradeInfoLogic>.Instance.FindAll(ht);

        IList<GlobalCauseInfo> sl = new List<GlobalCauseInfo>();
        foreach (GlobalCauseInfo info in subjectList)
        {
            foreach (CouseGradeInfo gradeInfo in cgList)
            {
                if (gradeInfo.CourseID == info.RID)
                {
                    sl.Add(info);
                    break;
                }
            }
        }

        #region 科目过滤
        List<GlobalCauseInfo> gcourseInfo = new List<GlobalCauseInfo>();
        List<int> enableSubjectList = SchoolCommon.CanViewClasses((int)SecurityTable.Security.Credit_CanView, SchoolCommon.Sch_SchoolInfo.SchoolYear, (int)SchoolCommon.Sch_SchoolInfo.SchoolTerm);
        if (!(enableSubjectList == null))
        {
            IList<GlobalCauseInfo> gcList = Container<ITeachClsCauseLogic>.Instance.GetTeacherCourse(Common.GetUserInfo().UID, SchoolMark);
            foreach (GlobalCauseInfo i in gcList)
            {
                foreach (GlobalCauseInfo gcInfo in sl)
                {
                    if (i.RID == gcInfo.RID)
                    {
                        gcourseInfo.Add(gcInfo);
                    }
                }
            }
            sl = gcourseInfo;
        }
        #endregion


        if (sl.Count < 1)
        {
            selSubject.Items.Add(new ListItem("没有科目数据", "-1"));
            return;
        }
        foreach (GlobalCauseInfo info in sl)
        {
            selSubject.Items.Add(new ListItem(info.CauseName, info.RID.ToString()));
        }
    }

    /// <summary>
    /// 绑定班级下拉框
    /// </summary>
    protected void BindClass(int schoolYear, int term)
    {
        selClass.Items.Clear();
        IList<ClsInfo> schoolList = Container<IClassHistoryLogic>.Instance.FindClassesInSchoolYear(schoolYear, SchoolMark, null);
        ListSort<ClsInfo> sortList = new ListSort<ClsInfo>(schoolList, "Grade");
        schoolList = sortList.Sort();
        if (schoolList == null || schoolList.Count < 1)
            return;

        foreach (ClsInfo info in schoolList)
        {
            String str = "";
            switch (info.Grade)
            {
                case 1:
                    str = "一年级";
                    break;
                case 2:
                    str = "二年级";
                    break;
                case 3:
                    str = "三年级";
                    break;
                case 4:
                    str = "四年级";
                    break;
                case 5:
                    str = "五年级";
                    break;
                case 6:
                    str = "六年级";
                    break;
                case 7:
                    str = "初一";
                    break;
                case 8:
                    str = "初二";
                    break;
                case 9:
                    str = "初三";
                    break;
                case 10:
                    str = "高一";
                    break;
                case 11:
                    str = "高二";
                    break;
                case 12:
                    str = "高三";
                    break;
            }

            #region 班级过滤
            List<int> enableClassList = SchoolCommon.CanViewClasses((int)SecurityTable.Security.Credit_CanView, schoolYear, term);
            bool enableClass = false;
            if (!(enableClassList == null))
            {
                foreach (int i in enableClassList)
                {
                    if (info.RID == i)
                    {
                        enableClass = true;
                        break;
                    }
                }
                if (!enableClass)
                    continue;
            }
            #endregion

            selClass.Items.Add(new ListItem(String.Format("{0}({1})班", str, info.ClsNo), info.RID.ToString()));
        }
        selClass_TextChanged(selClass, new EventArgs());
    }

    /// <summary>
    /// 学期下拉框事件
    /// </summary>
    protected void selYear_TextChanged(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            return;

        BindClass(nYear, nTerm);
    }

    /// <summary>
    /// 学期下拉框事件
    /// </summary>
    protected void selClass_TextChanged(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;
        int nClass = 0;

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            return;

        if (!Int32.TryParse(selClass.SelectedValue, out nClass))
            return;

        Hashtable ht = new Hashtable();
        ht.Add("RID", nClass);
        ht.Add("SchoolMark", SchoolMark);
        IList<ClsInfo> cilist = Container<IClsInfoLogic>.Instance.FindAll(ht);

        BindSubject(cilist[0].Grade);
    }

    /// <summary>
    /// 查询按钮事件
    /// </summary>
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;
        int nClass = 0;
        int nSubject = 0;

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            return;

        if (!Int32.TryParse(selClass.SelectedValue, out nClass))
            return;

        if (!Int32.TryParse(selSubject.SelectedValue, out nSubject))
            return;

        IList<int> causeList = new List<int>();
        causeList.Add(nSubject);

        IList<int> classList = new List<int>();
        causeList.Add(nClass);

        // 按月份的评价
        IList<StuCauseEvalState> stateList =
               Container<IStuCauseEvalHistoryLogic>.Instance.GetState(SchoolCommon.Sch_SchoolInfo.SchoolYear,
                                                                   SchoolCommon.Sch_SchoolInfo.SchoolTerm,
                                                                   SchoolMark, classList, nSubject);
        ListSort<StuCauseEvalState> sort = new ListSort<StuCauseEvalState>(stateList, "StartTime", false);
        stateList = sort.Sort();
        IList<DateTime> evalMonthList = new List<DateTime>();
        foreach (StuCauseEvalState state in stateList)
        {
            if (!evalMonthList.Contains(new DateTime(state.StartTime.Year, state.StartTime.Month, 1)))
                evalMonthList.Add(state.StartTime);
        }
        
        // 获取评价规则大类
        IList<StuCauseEvalType> evalTypeList =
            Container<IStuCauseEvalTypeLogic>.Instance.GetAllStuCauseEvalType(nSubject, SchoolMark, nYear, nTerm);

        // 获取期末成绩
        IList<TestScoreInTermView> testScoreList =
            Container<IClassResultExamListLogic>.Instance.FindTestScoreInTerm(SchoolMark, nYear, nTerm, null, nClass, causeList);

        // 获取学科学分成绩
        IList<CreditReport> causeScoreList =
            Container<IStuCausePersonCatchLogic>.Instance.GetCreditReport(SchoolMark, 0, nClass, nYear, nTerm);


        CreateTable(evalTypeList, testScoreList, causeScoreList, evalMonthList, nSubject);
    }

    /// <summary>
    /// 构造表格
    /// </summary>
    private void CreateTable(IList<StuCauseEvalType> evalTypeList, IList<TestScoreInTermView> testScoreList, IList<CreditReport> causeScoreList, IList<DateTime> evalMonthList, int nSubject)
    {
        causeFormula = new CauseFormula(SchoolMark, nSubject);
        causeLevelTool = new CauseLevelTool(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, SchoolMark);
        tbResult.Rows.Clear();
        
        int width = 0;
        int index = 1;
        #region 构造表头
        TableHeaderRow hrow = new TableHeaderRow();
        TableHeaderCell hcell = new TableHeaderCell();
        hcell.Text = "序号";
        hcell.Style[HtmlTextWriterStyle.Width] = "50px";
        hcell.CssClass = "FixedRowCol";
        width += 50;
        hrow.Cells.Add(hcell);

        hcell = new TableHeaderCell();
        hcell.Text = "学号";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        hcell.CssClass = "FixedRowCol";
        width += 70;
        hrow.Cells.Add(hcell);

        hcell = new TableHeaderCell();
        hcell.Text = "姓名";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        hcell.CssClass = "FixedRowCol";
        width += 70;
        hrow.Cells.Add(hcell);
        int nindex = 2;
        //// 加入月份列
        //if (evalMonthList != null)
        //{
        //    foreach (DateTime time in evalMonthList)
        //    {
        //        hcell = new TableHeaderCell();
        //        hcell.Text = String.Format("{0}月", time.Month);
        //        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        //        width += 70;
        //        hcell.CssClass = "FixedRow";
        //        hrow.Cells.Add(hcell);
        //        nindex++;
        //    }
        //}

        // 加入规则类别列
        if (evalMonthList != null)
        {
            foreach (StuCauseEvalType type in evalTypeList)
            {
                hcell = new TableHeaderCell();
                hcell.Text = type.Caption;
                hcell.Style[HtmlTextWriterStyle.Width] = "70px";
                width += 70;
                hcell.CssClass = "FixedRow";
                hrow.Cells.Add(hcell);
                nindex++;
            }
        }

        hcell = new TableHeaderCell();
        hcell.Text = "累计得分";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        width += 70;
        hcell.CssClass = "FixedRow";
        hrow.Cells.Add(hcell);

        hcell = new TableHeaderCell();
        hcell.Text = "平时学分";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        width += 70;
        hcell.CssClass = "FixedRow";
        hrow.Cells.Add(hcell);

        hcell = new TableHeaderCell();
        hcell.Text = "期末成绩";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        width += 70;
        hcell.CssClass = "FixedRow";
        hrow.Cells.Add(hcell);

        hcell = new TableHeaderCell();
        hcell.Text = "成绩学分";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        width += 70;
        hcell.CssClass = "FixedRow";
        hrow.Cells.Add(hcell);

        nindex += 5;
        hcell = new TableHeaderCell();
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        width += 70;
        hcell.CssClass = "FixedRow";
        hcell.Attributes.Add("onclick", String.Format("sort({0})", nindex));
        hcell.Text = "学期得分" + String.Format("<span id='img{0}'><img src='../../Common/images/1.gif' /></span>", nindex);
        hrow.Cells.Add(hcell);

        hcell = new TableHeaderCell();
        hcell.Text = "等级评定";
        hcell.Style[HtmlTextWriterStyle.Width] = "70px";
        width += 70;
        hcell.CssClass = "FixedRow";
        hrow.Cells.Add(hcell);

        tbResult.Rows.Add(hrow);
        tbResult.Style[HtmlTextWriterStyle.Width] = String.Format("{0}px", width);
        #endregion

        #region 填充表格内容
        int oldStudentID = -1;
        TableRow row = null;
        TableCell cell = null;
        IList<TableCell> monthCells = null;
        IList<TableCell> typeCells = null;
        TableCell sumScore = null;      // 累计得分单元格
        TableCell causeScore = null;    // 平时学分
        TableCell testScore = null;     // 期末成绩
        TableCell testCredit = null;    // 成绩学分
        TableCell termScore = null;     // 学期得分
        TableCell ranking = null;       // 等级评定
        double dbSumScore = 0;
        double dbCauseScore = 0;
        double dbTestCredit = 0;
        Dictionary<String, double> monthScoreList = null;
        Dictionary<String, double> typeScoreList = null;
        
        foreach (CreditReport report in causeScoreList)
        {
            if (report.StuID != oldStudentID)
            { // 新建一行 
                if (oldStudentID != -1)
                { // 统计上一行数据 
                    //// 填充月份列的分数
                    //foreach (TableCell monthCell in monthCells)
                    //{
                    //    if (monthScoreList.ContainsKey(monthCell.Attributes["month"]))
                    //    {
                    //        monthCell.Text = monthScoreList[monthCell.Attributes["month"]].ToString();
                    //    }
                    //    else
                    //    {
                    //        monthCell.Text = "0";
                    //    }
                    //    row.Cells.Add(monthCell);
                    //}
                    // 填充类别列的分数
                    foreach (TableCell typeCell in typeCells)
                    {
                        if (typeScoreList.ContainsKey(typeCell.Attributes["type"]))
                        {
                            dbSumScore += typeScoreList[typeCell.Attributes["type"]];
                            typeCell.Text = typeScoreList[typeCell.Attributes["type"]].ToString();
                        }
                        else
                            typeCell.Text = "0";
                        row.Cells.Add(typeCell);
                    }
                    // 填充累计得分
                    sumScore.Text = dbSumScore.ToString();
                    row.Cells.Add(sumScore);
                    // 填充平时学分
                    dbCauseScore = causeFormula.GetExpressScore(dbSumScore);
                    causeScore.Text = Math.Round(dbCauseScore, 2).ToString();
                    row.Cells.Add(causeScore);
                    // 期末成绩
                    
                    row.Cells.Add(testScore);
                    // 成绩学分
                    
                    row.Cells.Add(testCredit);
                    // 填充学期学分
                    termScore.Text = Math.Round((dbCauseScore + dbTestCredit), 2).ToString();
                    row.Cells.Add(termScore);
                    // 等级评定
                    ranking.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear, 
                        SchoolCommon.Sch_SchoolInfo.SchoolTerm, 
                        (dbCauseScore + dbTestCredit));
                    row.Cells.Add(ranking);

                    tbResult.Rows.Add(row);
                }
                dbSumScore = 0;
                dbCauseScore = 0;
                monthScoreList = new Dictionary<String, double>();
                typeScoreList = new Dictionary<String, double>();
                row = new TableRow();
                // 序号列
                cell = new TableCell();
                cell.Text = index.ToString();
                cell.CssClass = "FixedCol";
                row.Cells.Add(cell);
                // 学号列
                cell = new TableCell();
                cell.Text = report.StuCode.ToString();
                cell.CssClass = "FixedCol";
                row.Cells.Add(cell);
                // 姓名列
                cell = new TableCell();
                cell.Text = report.StuName.ToString();
                cell.CssClass = "FixedCol";
                row.Cells.Add(cell);
                //// 月份列
                //monthCells = new List<TableCell>();
                //foreach (DateTime time in evalMonthList)
                //{
                //    cell = new TableCell();
                //    cell.Attributes.Add("month", time.ToString("yyyy-MM"));
                //    monthCells.Add(cell);
                //}
                // 类别列
                typeCells = new List<TableCell>();
                foreach (StuCauseEvalType type in evalTypeList)
                {
                    cell = new TableCell();
                    cell.Attributes.Add("type", type.RID.ToString());
                    typeCells.Add(cell);
                }
                // 累计得分
                sumScore = new TableCell();
                // 平时学分
                causeScore = new TableCell();
                // 期末成绩
                testScore = new TableCell();
                TestScoreInTermView ts = (testScoreList as List<TestScoreInTermView>).Find(delegate(TestScoreInTermView c) { return c.StuID == report.StuID; });
                testScore.Text = (ts != null && ts.Score.HasValue) ? Math.Round(ts.Score.Value, 2).ToString() : "0";
                // 成绩学分
                testCredit = new TableCell();
                dbTestCredit = causeFormula.GetTestScore((ts != null && ts.Score.HasValue) ? ts.Score.Value : 0);
                testCredit.Text = Math.Round(dbTestCredit, 2).ToString();
                // 学期得分
                termScore = new TableCell();
                // 等级评定
                ranking = new TableCell();
                index++;
            }
            //// 月份计算
            //String strDate = report.StartTime.ToString("yyyy-MM");
            //if (nSubject == report.CauseID)
            //{
            //    if (!monthScoreList.ContainsKey(strDate))
            //        monthScoreList.Add(strDate, report.TypeScore);
            //    else
            //        monthScoreList[strDate] += report.TypeScore;
            //}

            // 类别计算
            String strTypeID = report.TypeID.ToString();
            if (!typeScoreList.ContainsKey(strTypeID))
                typeScoreList.Add(strTypeID, report.TypeScore);
            else
                typeScoreList[strTypeID] += report.TypeScore;

            oldStudentID = report.StuID;
        }
        foreach (TableCell typeCell in typeCells)
        {
            if (typeScoreList.ContainsKey(typeCell.Attributes["type"]))
            {
                dbSumScore += typeScoreList[typeCell.Attributes["type"]];
                typeCell.Text = typeScoreList[typeCell.Attributes["type"]].ToString();
            }
            else
                typeCell.Text = "0";
            row.Cells.Add(typeCell);
        }
        // 填充累计得分
        sumScore.Text = dbSumScore.ToString();
        row.Cells.Add(sumScore);
        // 填充平时学分
        dbCauseScore = causeFormula.GetExpressScore(dbSumScore);
        causeScore.Text = Math.Round(dbCauseScore, 2).ToString();
        row.Cells.Add(causeScore);
        // 期末成绩

        row.Cells.Add(testScore);
        // 成绩学分

        row.Cells.Add(testCredit);
        // 填充学期学分
        termScore.Text = Math.Round((dbCauseScore + dbTestCredit), 2).ToString();
        row.Cells.Add(termScore);
        // 等级评定
        ranking.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear,
            SchoolCommon.Sch_SchoolInfo.SchoolTerm,
            (dbCauseScore + dbTestCredit));
        row.Cells.Add(ranking);
        tbResult.Rows.Add(row);
        if (oldStudentID != -1)
        { // 统计上一行数据 
            //// 填充月份列的分数
            //foreach (TableCell monthCell in monthCells)
            //{
            //    if (typeScoreList.ContainsKey(monthCell.Attributes["month"]))
            //    {
            //        dbSumScore += monthScoreList[monthCell.Attributes["month"]];
            //        monthCell.Text = monthScoreList[monthCell.Attributes["month"]].ToString();
            //    }
            //}
            // 填充类别列的分数
            foreach (TableCell typeCell in typeCells)
            {
                if (typeScoreList.ContainsKey(typeCell.Attributes["type"]))
                    typeCell.Text = typeScoreList[typeCell.Attributes["type"]].ToString();
            }
            // 填充累计得分
            sumScore.Text = dbSumScore.ToString();
            // 填充平时学分
            dbCauseScore = causeFormula.GetExpressScore(dbSumScore);
            causeScore.Text = Math.Round(dbCauseScore, 2).ToString();
            // 填充学期学分
            termScore.Text = Math.Round((dbCauseScore + dbTestCredit), 2).ToString();
            // 等级评定
            ranking.Text = causeLevelTool.GetCauseLevel(SchoolCommon.Sch_SchoolInfo.SchoolYear,
                SchoolCommon.Sch_SchoolInfo.SchoolTerm,
                (dbCauseScore + dbTestCredit));
        }
        #endregion
    }

    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "download\\" + DateTime.Now.Ticks + "_profile.xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, DateTime.Now.Ticks + "学分单科学期汇总", 1, 0, cells);
        return "";
    }
}
